package com.whosly.mysql.protocol.packet.impl;

import com.whosly.mysql.protocol.jdbc.MySQLMessage;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;

/**
 * <pre>
 *   Bytes                        Name
 *   -----                        ----
 *   1                            command
 *   string[NULL]                 table
 *   string[EOF]                  field wildcard
 * </pre>
 *
 * COM_FIELD_LIST
 * @author fengyang
 * @date 2023年06月25日 上午10:14
 */
@Slf4j
public class FieldListCommandPacket extends NettyCommandPacket
{
    /**
     * 表名
     */
    public String tableName;

    /**
     * 字段通配符
     */
    public String fieldWildcard;

    @Override
    public void read(byte[] bodyBytes)
    {
        readBody(bodyBytes);
    }

    public void read(byte[] bodyBytes, String charset)
    {
        readBody(bodyBytes, charset);
    }

    @Override
    protected void readBody(byte[] bodyBytes) {
        readBody(bodyBytes, null);
    }

    private void readBody(byte[] bodyBytes, String charset) {
        MySQLMessage mm = new MySQLMessage(bodyBytes);

        setCmd(mm.read());
        setArg(mm.readBytes());

        // arg解析表名及字段通配符
        MySQLMessage para = new MySQLMessage(getArg());
        byte[] tableNameBytes = para.readBytesWithNull();
        byte[] fieldWildcardBytes = para.readBytes();

        try {
            if (charset == null) {
                this.tableName =  new String(tableNameBytes);
                this.fieldWildcard = new String(fieldWildcardBytes);
            } else  {
                this.tableName =  new String(tableNameBytes, charset);
                this.fieldWildcard = new String(fieldWildcardBytes, charset);
            }
        } catch (UnsupportedEncodingException e) {
            log.error("FIELD LIST COMMAND PACKET error:", e);
        }
    }
}
